/*
 * Gsoft开发框架
 * Copyright 2015-2020 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.itcncp.ipaybox.server.service.impl;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.itcncp.common.ipaybox.BoxConstants;
import com.itcncp.common.ipaybox.model.BoxRequest;
import com.itcncp.ipaybox.server.resolver.MsgResolverAdapter;
import com.itcncp.ipaybox.server.service.NettyMsgResolveService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSON;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;

/**
 * netty消息解析
 * 
 * @author LiuPeng
 * @date 2017年12月12日
 * 
 */
@Component
public class NettyMsgResolveServiceImpl implements NettyMsgResolveService, ApplicationContextAware {

	private Log logger = LogFactory.getLog(getClass());

	private List<MsgResolverAdapter> resolverAdapters;

	@Override
	public void resolve(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) {

		try {
			String paramJson = getDecode(byteBuf);
			BoxRequest boxRequest = JSON.parseObject(paramJson, BoxRequest.class);

			for (MsgResolverAdapter resolverAdapter : resolverAdapters) {
				if (resolverAdapter.support(boxRequest)) {
					resolverAdapter.resolve(channelHandlerContext, boxRequest);
				}
			}
		} catch (Exception e) {
			// TODO: 异常处理
			e.printStackTrace();
		}

	}

	public String getDecode(ByteBuf byteBuf) {
		String jsonString = byteBuf.toString( BoxConstants.CHARSET_UTF8).trim();
		// 测试工具编码为gb2312 如果是测试工具将进行转码
		if (jsonString.contains("�")) {
			jsonString = byteBuf.toString(Charset.forName("gb2312")).trim();
		}
		return jsonString;
	}

	/*
	 * (非 Javadoc) <p>Title: setApplicationContext</p> <p>Description: </p>
	 * 
	 * @param arg0
	 * 
	 * @throws BeansException
	 * 
	 * @see
	 * org.springframework.context.ApplicationContextAware#setApplicationContext(org
	 * .springframework.context.ApplicationContext)
	 */
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		initResolverAdapters(applicationContext);
	}

	/**
	 * 初始化resolverAdapters
	 * 
	 * @param applicationContext
	 */
	private void initResolverAdapters(ApplicationContext applicationContext) {
		if (resolverAdapters == null) {
			Map<String, MsgResolverAdapter> beanMap = BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext,
					MsgResolverAdapter.class, true, false);
			resolverAdapters = new ArrayList<>(beanMap.size());
			for (Map.Entry<String, MsgResolverAdapter> entry : beanMap.entrySet()) {
				resolverAdapters.add(entry.getValue());
			}
			logger.info("初始化netty解析适配器完成:" + resolverAdapters.size());
		}
	}

}
